package com.project.erp.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

/**
 * cookies 工具类
 * @author zyj
 *
 */
public class CookieUtil {
	
	/**
	 * 根据名称获取cookies名称
	 * @param request request
	 * @param name 名称
	 * @return cookie
	 */
	public static Cookie getCookie(HttpServletRequest request,String name){
		Cookie[] cookies = request.getCookies();
		if(cookies == null || StringUtils.isEmpty(name)){
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			if(name.equals(cookies[i].getName())){
				return cookies[i];
			}
		}
		return null;
	}
	
	public static String getCookieValue(HttpServletRequest request,String name){
		Cookie[] cookies = request.getCookies();
		if(cookies == null || StringUtils.isEmpty(name)){
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			if(name.equals(cookies[i].getName())){
				if(null != cookies[i]){
					return cookies[i].getValue();
				}else{
					return null;
				}
			}
		}
		return null;
	}
	
	/**
	 * 删除cookie信息
	 * @param request
	 * @param response
	 * @param cookie
	 */
	public static void deleteCookie(HttpServletRequest request,HttpServletResponse response,Cookie cookie){
		if(cookie != null){
			cookie.setPath(getPath(request));
			cookie.setValue("");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}
	
	/**
	 * 设置cookie信息
	 * @param request
	 * @param response
	 * @param name
	 * @param value
	 */
	public static void setCookie(HttpServletRequest request,HttpServletResponse response, String name, String value) {
		setCookie(request, response, name, value, 0x278d00);
	}
	
	/**
	 * 设置cookie信息
	 * @param request
	 * @param response
	 * @param name
	 * @param value
	 * @param maxAge
	 */
	public static void setCookie(HttpServletRequest request,HttpServletResponse response, String name, String value,int maxAge){
		Cookie cookie = new Cookie(name, value == null ? "" : value);
	    cookie.setMaxAge(maxAge);
	    cookie.setPath(getPath(request));
	    response.addCookie(cookie);
	}
	
	/**
	 * 获取服务器路径
	 * @param request
	 * @return
	 */
	private static String getPath(HttpServletRequest request) {
		String path = request.getContextPath();
		return (path == null || path.length()==0) ? "/" : path;
	}
}
